package service.facade.user;

import dao.inte.ConfigurationRepository;
import dao.inte.UserRepository;
import domain.User;
import exceptions.UserAlreadyExistsException;
import org.jasypt.util.password.PasswordEncryptor;
import org.springframework.transaction.annotation.Transactional;
import service.ILoggerService;
import service.mail.Mailer;
import service.velocity.VelocityService;
import web.admin.config.DirectoryPathException;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;

@Transactional
@Singleton
public class UserServiceImpl implements UserService {

    @Inject
    private VelocityService velocityService;
    @Inject
    UserRepository userRepository;
    @Inject
    Mailer mailer;
    @Inject
    ConfigurationRepository configurationRepository;
    @Inject
    PasswordEncryptor passwordEncryptor;
    @Inject
    private ILoggerService loggerService;

    public UserServiceImpl() {
    }

    public UserServiceImpl(VelocityService velocityService, UserRepository userRepository, Mailer mailer, ConfigurationRepository configurationRepository) {
        this.velocityService = velocityService;
        this.userRepository = userRepository;
        this.mailer = mailer;
        this.configurationRepository = configurationRepository;
    }


    public User findUserById(long userId) {
        return userRepository.findById(userId);
    }

    public User findUserByLogin(String userName) throws NonUniqueResultException {
        return userRepository.findByLogin(userName);
    }


    @Transactional(rollbackFor = DirectoryPathException.class, noRollbackFor = NoResultException.class)
    public void registration(User user) throws UserAlreadyExistsException, Exception {


        if (userRepository.findByLogin(user.getLogin()) != null) {  // (musi bejt nastaveny noRollbackFor =  NoResultException.class)
            throw new UserAlreadyExistsException();
        }


        userRepository.save(user);

        String recipients[] = {user.getCompanyEmail()};
        String subject = configurationRepository.getConfig().getRegistrationMailSubject();
        String message = velocityService.getRegistrationMail(user);
        String from = configurationRepository.getConfig().getAdministratorEmail();

        mailer.postMail(recipients, subject, message, from);

    }

    public boolean changePassword(User object, String oldPassword, String newPassword) throws Exception {
        loggerService.log(ILoggerService.ActionType.PASSWORD_CHANGE_REQUEST);

        final User user = userRepository.findById(object.getId());
        if (passwordEncryptor.checkPassword(oldPassword, user.getPassword())) {
            user.setPassword(newPassword);
            userRepository.save(user);
            return true;
        }
        return false;

    }


}
